<!-- components/CrudModal.vue -->
<template>
  <a-modal
      :title="titleMap[mode]"
      :open="visible"
      :confirm-loading="loading"
      @ok="handleOk"
      @cancel="handleCancel"
      destroy-on-close
      :maskClosable="false"
  >
    <a-form
        :model="formData"
        ref="formRef"
        layout="vertical"
    >
      <a-form-item
          v-for="field in formConfig"
          :key="field.key"
          :label="field.label"
          :name="field.key"
          :rules="field.rules || []"
      >
        <component
            :is="getComponent(field.type).name"
            v-model:value="formData[field.key]"
            v-bind="{
            ...getComponent(field.type).defaultProps,
            ...(field.props || {}),
            disabled: field.disabled
          }"
        />
        <div style="color: rgba(0, 0, 0, 0.4);font-size: 12px;line-height: 1.5" v-if="field.tip">
          {{ field.tip }}
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import {ref, reactive, defineExpose, watch} from "vue";
import ImageUpload from "../ImageUpload/ImageUpload.vue";

// ✅ 接收结构配置和提交事件
const props = defineProps({
  formConfig: {type: Array, required: true}, // [{ key, label, type, rules, props, disabled, defaultValue }]
  mode: {type: String, default: "add"}, // add | edit
  onSubmit: {}
});

const visible = ref(false);
const loading = ref(false);
const formRef = ref(null);
const formData = reactive({});

const titleMap = {
  add: "新增数据",
  edit: "编辑数据",
};

import {Input} from "ant-design-vue";

function getComponent(type) {
  switch (type) {
    case "select":
      return {
        name: "a-select",
        defaultProps: {
          style: {width: "100%"},
          allowClear: true,
          placeholder: "请选择",
        },
      };
    case "date":
      return {
        name: "a-date-picker",
        defaultProps: {
          style: {width: "100%"},
        },
      };
    case "textarea":
      return {
        name: "a-textarea",
        defaultProps: {
          style: {width: "100%"},
          autoSize: {minRows: 3, maxRows: 5},
          placeholder: "请输入",
        },
      };
    case "image-upload":
      return {
        name: ImageUpload,
        defaultProps: {
          accept: "image/*",
        }
      };
    case "password":
      return {
        name: "a-input-password",
        defaultProps: {
          style: {width: "100%"},
        },
      };
    default:
      return {
        name: "a-input",
        defaultProps: {
          style: {width: "100%"},
          allowClear: true,
          placeholder: "请输入",
        },
      };
  }
}


// ✅ 提供外部调用 open() 方式
function open(initialData = {}) {
  visible.value = true;
  loading.value = false;
  resetForm(initialData);
}

function resetForm(initialData = {}) {
  Object.keys(formData).forEach(key => delete formData[key]); // 清空旧数据
  props.formConfig.forEach(field => {
    formData[field.key] = initialData[field.key] ?? field.defaultValue ?? "";
  });
  console.log("formData",formData)
}

async function handleOk() {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    // 👇 显式调用 props.onSubmit
    await props.onSubmit(props.mode, {...formData});
    visible.value = false;
  } catch (e) {
    console.error("表单提交失败：", e);
  } finally {
    loading.value = false;
  }
}

function handleCancel() {
  visible.value = false;
}

// ✅ 暴露 open() 方法给父组件使用
defineExpose({open});
</script>
